<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2023/4/20
 * Time: 23:33
 */

namespace app\backstage\server;

use OSS\OssClient;
use think\facade\Env;

/**
 * 上传服务
 * Class UploadServer
 * @package app\backstage\server
 */
class UploadServer
{

    /**
     * 上传oss
     * @param $filename
     * @param $filepath
     * @return string
     * @throws \OSS\Core\OssException
     * @Author: whh
     */
    public function putFileToOss($filename, $filepath, $dirName = 'novel')
    {
        $dirName = 'quick_cms/' . $dirName;
        $filename = $dirName . '/' . date('Ymd') . '/' . $filename;
        $kv['AccessKeyID'] = config('oss_accessKeyID');
        $kv['AccessKeySecret'] = config('oss_accessKeySecret');
        $kv['OSS_ENDPOINT'] = config('oss_endPoint');
        $kv['OSS_BUCKET'] = config('oss_bucket');
        $ossClient = new OssClient($kv['AccessKeyID'], $kv['AccessKeySecret'], $kv['OSS_ENDPOINT']);
        $rs = $ossClient->uploadFile($kv['OSS_BUCKET'], $filename, $filepath);
        if (isset($rs['oss-request-url'])) {
            $arr = explode($dirName, $rs['oss-request-url']);
            $rs['shortpath'] = $arr[1];
        }
        @unlink($filepath);
        return "/" . $dirName . $rs['shortpath'];
    }

    /**
     * 下载图片
     * @param $picUrl
     * @param $path
     * @param $filename
     * @return string
     * @Author: whh
     */
    public function downLoadPic($picUrl, $path, $filename)
    {
        $curl = curl_init();
        $fp = fopen($path . $filename, 'w');
        curl_setopt($curl, CURLOPT_URL, $picUrl);
        curl_setopt($curl, CURLOPT_FILE, $fp);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip, deflate');
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $headers [] = 'Accept: textml,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $headers [] = 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3';
        $headers [] = 'Connection: keep-alive';
        $headers [] = 'Cache-Control: max-age=0';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($curl);
        curl_close($curl);
        fclose($fp);
        if ($res) {
            $filepath = $path . $filename;
            $size = filesize($filepath);
            if ($size > 512000) {
                $filepath = $this->compress($filepath);//图片大于500kb就压缩
            }
            $ossPath = $this->putFileToOss($filename, $filepath);
            return $ossPath;
        } else {
            return '';
        }
    }

    /**
     * 压缩图片
     * @param $filename
     * @return string
     * @Author: whh
     */
    public function compress($filename)
    {
        // 源文件
        $percent = 1;
        // Content type
        header('Content-Type: image/jpeg');
        // Get new dimensions
        list($width, $height) = getimagesize($filename);
        $new_width = $width * $percent;
        $new_height = $height * $percent;
        // Resample
        $image_p = imagecreatetruecolor($new_width, $new_height);
        $suffix = $this->getExtension($filename);
        if (strpos($suffix, 'png')) {
            $image = imagecreatefrompng($filename);
        } else {
            $image = imagecreatefromjpeg($filename);
        }
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        // Output
        imagedestroy($image);
        $path = Env::get('ROOT_PATH') . "uploads" . "/" . date("Ymd", time()) . "_compress" . "/";
        if (!file_exists($path)) {
            mkdir($path, 0777);
        }
        $image_p_path = md5(rand(1, 99999999)) . $suffix;
        imagejpeg($image_p, $image_p_path);
        @unlink($filename);
        return $image_p_path;
    }

    /**
     * 获取后缀
     * @param $file
     * @return string
     * @Author: whh
     */
    public function getExtension($file)
    {
        $info = pathinfo($file);
        $extension = 'jpg';
        if (isset($info['extension']) && $info['extension'] != '') {
            $extension = $info['extension'];
        }
        return '.' . $extension;
    }



    /**
     * 读取章节内容txt
     * @param $txt_path
     * @return array
     * @Author: whh
     */
    public function getContentByFile($txt_path)
    {
        if (strlen($txt_path) < 1) {
            return ['code' => 0, 'msg' => '章节内容txt未上传', 'data' => []];
        }

        $max_len = 75;
        $pregArray = array();

        //规则  【第一百五十四章 xxx】  【第001章 xxx】
        $preg['rule'] = '#(.*?)第[\s\S]{1,30}章(.*?)#ims';
        $preg['maxlen'] = 90;
        $pregArray[] = $preg;
        //规则  【001 xxx】
        /*$preg['rule']   = '#^\d{1,6}(.+?)$#';
        $preg['maxlen'] = 70;
        $pregArray[]    = $preg;*/
        //规则  【001】
        /*$preg['rule']   = '#^\d{1,6}$#';
        $preg['maxlen'] = 10;
        $pregArray[]    = $preg;*/
        //增加规则  如果存在【###】  或者 【####】 就认为是标题

        // 新增规则：匹配单纯的数字章节名
        $preg['rule'] = '#^\d+$#';
        $preg['maxlen'] = 10;
        $pregArray[] = $preg;

        $file_path = $txt_path;

        $file = fopen($file_path, "rb");

        if (!$file) {
            return ['code' => 1, 'msg' => '上传失败，请确定上传文件格式为utf-8格式！'];
        }

        $chapterlist = array();
        $chapter = array();
        $isbegin = false;
        $content = $cname = $lastcname = $getcname = $lastgetcname = $author = $cover = $brief = '';
        $update_status = 0;
        $fastPayChapter = 7;
        while (!feof($file)) {

            $line = fgets($file);
            $line = str_replace('(', '（', $line);
            $line = str_replace(')', '）', $line);

            if (!$isbegin) {

                if (!$this->check_is_Utf8($line)) {
                    return ['code' => 2, 'msg' => '文件格式不对，请使用UTF8格式上传!'];
                }
            }

            $ruleline = preg_replace(array('/　　/', '/　/', '/　/'), '', trim($line));

            foreach ($pregArray as $v) {
                $res = preg_match($v['rule'], $ruleline, $match);
                $max_len = $v['maxlen'];
                if ($res) {
                    break;
                }
            }

            //增加规则  如果存在【###】  或者 【####】 而且在一开始的位置就认为是标题
            $isTitle = false;
            $getjh1 = stripos($ruleline, '####');
            $getjh2 = stripos($ruleline, '###');

            if (strstr($ruleline, '####') && $getjh1 == 0) {
                $isTitle = true;
            } else if (strstr($ruleline, '###') && $getjh2 == 0) {
                $isTitle = true;
            } else if (strstr($ruleline, '#')) {
                //如果存在#字符 则人为判断该行不是标题，需要手动设置
                $res = false;
            }

            if (strstr($ruleline, '作者:')) {
                $author = trim(substr($line, strripos($line, "作者:") + 7));
            }
            if (strstr($ruleline, '更新进度:')) {
                $str = trim(substr($line, strripos($line, "更新进度:") + 13));
                if ($str == '完本') {
                    $update_status = 1;
                }
            }
            if (strstr($ruleline, '开始收费章节:')) {
                $str = trim(substr($line, strripos($line, "开始收费章节:") + 19));
                if ($str) {
                    $fastPayChapter = $str;
                }
            }
            if (strstr($ruleline, '简介:')) {
                $brief = trim(substr($line, strripos($line, "简介:") + 7));
            }
            if (strstr($ruleline, '封面:')) {
                $imgUrl = trim(substr($line, strripos($line, "封面:") + 7));
                $addTime = date("Ymd", time());
                $path = Env::get('ROOT_PATH') . 'uploads/' . $addTime . "/";
                if (!file_exists($path)) {
                    mkdir($path, 0777);
                }
                $server = new UploadServer();
                $filename = md5(rand(1, 99999999)) . $server->getExtension($imgUrl);
                $cover = $server->downLoadPic($imgUrl, $path, $filename);
            }

            if ($isTitle || ($res && strlen(trim($ruleline)) < $max_len)) {
                $lastcname = $cname;
                $lastgetcname = $getcname;

                $cname = str_replace('####', '', $ruleline);
                $cname = str_replace('###', '', $cname);
                $getcname = $cname;
                if ($isbegin) {
                    $chapter['cname'] = $lastcname;
                    $chapter['getcname'] = $lastgetcname;
                    $chapter['content'] = $content;
                    $chapterlist[] = $chapter;
                    $content = '';
                }

                $isbegin = true;

            } else {
                if ($isbegin) {
                    $content .= $line . "\n";
                }
            }
        }
        $chapter['cname'] = $cname;
        $chapter['getcname'] = $getcname;
        $chapter['content'] = $content;
        $chapterlist[] = $chapter;
        fclose($file);

        unlink($file_path);
        return ['code' => 0, 'msg' => 'ok', 'data' => [
            'info' => [
                'author' => $author,
                'cover' => $cover,
                'brief' => $brief,
                'update_status' => $update_status,
                'fastPayChapter' => $fastPayChapter,
            ],
            'chapters' => $chapterlist
        ]];
    }

    /**
     * @param $str
     * @return bool
     * @Author: whh
     */
    function check_is_Utf8($str)
    {
        $charset = mb_detect_encoding($str, array('UTF-8', 'GBK', 'GB2312', 'BIG-5'));
        $charset = strtolower($charset);
        if ($charset != 'utf-8') {
            return false;
        }
        return true;
    }


}